package com.group3.merchant.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group3.entity.Merchant;

/**
 * Servlet Filter implementation class MerchantStatusFilter
 */
public class MerchantStatusFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public MerchantStatusFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		Merchant merchant = (Merchant) session.getAttribute("loginToken");
		String mid = merchant.getmId();
		Map<String, String> amap = (Map<String, String>) req
				.getServletContext().getAttribute(mid);
		System.out.println("Filter mid: " + mid);
		System.out.println("Filter amap: " + amap);
		if(amap!=null){
			String status = amap.get("mstatus");
			if(!"".equals(status)){
				status = status.toLowerCase();
			}
			
			// pass the request along the filter chain
			System.out.println("status : " + status);
			
			if ("black".equals(status)) {
//				req.getSession().setAttribute("MStatus", status);
//				req.getServletContext().setAttribute(mid, amap);
				req.getSession().setAttribute("mstatus", status);
				req.getRequestDispatcher("pending.jsp").forward(req, response);
			} else {
				chain.doFilter(req, response);
			}
		}else{
//			chain.doFilter(req, response);
			HttpServletResponse res = (HttpServletResponse)response;
			res.sendRedirect("login.jsp");
		}
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
